<?php

/**
 * @author LSH 2013-04-21 
 *  豆瓣授权页 ..
 *  关于豆瓣的操作必须经过豆瓣授权之后才能进行..
 */
class Douban extends MY_Controller{
	
	public $m_openID  = 0;
	public $m_myToken   = null;
	public $m_myOutTime = null;
	
	
	// 平台编号 ..
	public static $m_platformId = DOUBAN_TYPE;
	
	
	public static $m_config = array(
            // 必选参数，豆瓣应用public key。
            'client_id' => null,
            // 必选参数，豆瓣应用secret key。
            'secret' => null,
            // 必选参数，用户授权后的回调链接。
            'redirect_uri' => null,
            // 可选参数（默认为douban_basic_common），授权范围。
            'scope' => 'douban_basic_common,shuo_basic_r,shuo_basic_w,community_advanced_doumail_w',
            // 可选参数（默认为false），是否在header中发送accessToken。
            'need_permission' => true,
            );
	
	public function __construct()
	{
		parent::__construct();
		
		if (empty($this->m_arrUser))
		{
			redirect('account/login?reUrl=index.php/douban/apikey');
			exit;
		}
		
		$filter = array(
				'accountID' => $this->m_arrUser['id'],
				'platformID' => self::$m_platformId,
		);
			
		$acc2platList = $this->account_m->getPlatfromList($filter);
		
		// 未填写key 和secret
		if ($acc2platList[0]['myKey'] == null || $acc2platList[0]['mySecret'] == null)
		{
			redirect('douban/'.self::$apikey);
			exit;
		}
		
		self::$m_config['redirect_uri'] = BASE_URL.'/index.php/oauth2/sdouban/callback';
		self::$m_config['client_id']    = $acc2platList[0]['myKey'];
		self::$m_config['secret']       = $acc2platList[0]['mySecret'];
		
		// 生成一个豆瓣Oauth类实例
		
		$this->load->library('Douban/MY_DoubanOauth',self::$m_config);
			
		// 载入session
		$this->load->library('session');
		
		// 载入model
		$this->load->model('account/account_m');
	}
	public function index()
	{
		
		// 如果没有authorizeCode，跳转到用户授权页面
		if ( ! isset($_GET['code'])) {
			$this->my_doubanoauth->requestAuthorizeCode();
			exit;
		}
	
		
	}
	
	public function callback()
	{
		// 设置authorizeCode
		$this->my_doubanoauth->setAuthorizeCode($_GET['code']);
		
		// 通过authorizeCode获取accessToken，至此完成用户授权
		$arrDouban = $this->my_doubanoauth->requestAccessToken();
		
		// 授权成功
		if (is_array($arrDouban) || isset($arrDouban['access_token']))
		{
			$this->m_openID     = $arrDouban['douban_user_id'];
			$this->m_myToken    = $arrDouban['access_token'];
			$this->m_myOutTime  = $arrDouban['expires_in'];
			
			// 判断是否已经绑定 ...
			$updateData = array(
					'openID'    => $this->m_openID,
					'myToken'   => $this->m_myToken,
					'myOutTime' => $this->m_myOutTime,
						
			);
			$this->account_m->setPlatform($accountID,self::$m_platformId,$updateData);
		}
		else
		{
			echo '出错了..';
			
			print_r($arrDouban);
		}
		
		
	}
	
}